package com.aote.model.block;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import com.aote.reportforms.Reportforms;
import com.aote.reportforms.ReportformsFactory;
import com.browsesoft.EntityManager;
import com.browsesoft.ExtendElement;
import com.browsesoft.baseadapter.SimpleEntity;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.parameter.Parameter;

public class EntitiesDatasBlockModel implements
		EntitiesDatasBlockModelInterface {

	/**
	 * 数据 key：nrowncol value ：数据值
	 */
	private Hashtable blockDatas = new Hashtable();

	/**
	 * 实体
	 */
	private List entities = new LinkedList();

	/**
	 * 组件
	 */
	private HTMLBasicComponent component = null;

	/**
	 * 请求中的参数parentid
	 */
	private String parentId = "";

	/**
	 * 是否只读
	 */
	private String readOnly = "";

	/**
	 * 动作标识action
	 */
	private String action = "";

	/**
	 * 初始化model
	 */
	public void init(HttpServletRequest request) throws Exception {
		this.parentId = request.getParameter("parentid");
		this.readOnly = request.getParameter("readonly");
	}

	/**
	 * 根据实体类型得到实体
	 * 
	 * @throws Exception
	 */
	private List getEntities() {
		String entityType = this.component.getElement().getAttribute(
				"entitytype");
		List result = new LinkedList();
		Hashtable ht = new Hashtable();
		ht.put("entitytype", entityType);
		try {
			result = EntityManager.getInstance().getObjects(
					"com.browsesoft.baseadapter.SimpleEntity", ht);
		} catch (Exception e) {
			throw new RuntimeException();
		}
		return result;
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 得到数据
		this.entities = getEntities();
		this.blockDatas = getDatas();
		// 如果是提交，插入或更新报表数据
		action = request.getParameter("action");
		if (action != null && action.equals("confirm")) {
			// 更新临时数据
			updateTempDatas(request);
			// 计算

		}
	}

	/**
	 * 保存报表
	 */
	private void saveReportforms() {
		// 如果是创建
		if (this.isCreate()) {
			ReportformsFactory.getInstance().insert(this.parentId,
					this.blockDatas);
		} else {
			ReportformsFactory.getInstance().update(this.parentId,
					this.blockDatas);
		}
	}

	/**
	 * 更新数据
	 */
	private void updateTempDatas(HttpServletRequest request) {
		Iterator iter = this.blockDatas.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			String newValue = request.getParameter(key);
			if (newValue != null) {
				this.blockDatas.put(key, newValue);
			}
		}
	}

	/**
	 * 是否是创建
	 */
	private boolean isCreate() {
		Reportforms rf = ReportformsFactory.getInstance().getReportforms(
				this.parentId);
		if (rf != null) {
			return false;
		}
		return true;
	}

	/**
	 * 根据id得到数据
	 */
	private Hashtable getDatas() {
		Hashtable result = new Hashtable();
		Reportforms report = ReportformsFactory.getInstance().getReportforms(
				this.parentId);
		if (report != null) {
			result = report.getAttributes();
		}
		return result;
	}

	public void modifyCellValue(Element td, Document doc, int row, int col) {
		if (this.isRead()) {
			String data = (String) this.blockDatas.get(row + "row" + col
					+ "col");
			ExtendElement.removeChilds(td);
			Node node = td.getOwnerDocument().createTextNode(data);
			td.appendChild(node);
		} else {
			setTdInitValue(td, row, col);
		}
	}

	/**
	 * 设置td初始值
	 */
	private void setTdInitValue(Element td, int row, int col) {
		try {

			Element elem = (Element) td.getFirstChild();
			String name = row + "row" + col + "col";
			elem.setAttribute("name", name);
			if (!this.blockDatas.keySet().contains(name)) {
				this.blockDatas.put(name, "");
			}
			if (elem.getTagName().equals("select")) {
				setSelectValue(elem, row, col);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 设置选择框内容
	 * 
	 */
	public void setSelectValue(Element selectElem, int row, int col)
			throws Exception {
		// 如果有参数标记
		if (selectElem.hasAttribute("param")) {
			// 得到参数 参数值
			Parameter parameter = new Parameter(selectElem
					.getAttribute("param"));
			Iterator options = parameter.getParamValues().iterator();
			ExtendElement.removeChilds(selectElem);
			while (options.hasNext()) {
				Element element = this.component.getPage().getDocument()
						.createElement("option");
				selectElem.appendChild(element);
				String context = options.next().toString();
				Text text = this.component.getPage().getDocument()
						.createTextNode(context);
				element.appendChild(text);
			}
		}
		setDefaultValue(selectElem, row, col);
	}

	/**
	 * 如果是被选中的，设置selected选项
	 */
	public void setDefaultValue(Element dealElement, int row, int col)
			throws Exception {
		// 得到属性值
		String value = (String) this.blockDatas.get(row + "row" + col + "col");
		NodeList nodelist = dealElement.getChildNodes();
		for (int i = 0; i < nodelist.getLength(); i++) {
			// 是OPTION元素
			if (nodelist.item(i).getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) nodelist.item(i);
				Text text = (Text) ExtendElement.findElementContext(element)
						.get(0);
				String context = (String) text.getData();
				if (context.equals(value)) {
					element.setAttribute("selected", "selected");
				}
			}
		}
	}

	/**
	 * 是否是只读
	 */
	private boolean isRead() {
		if (this.readOnly != null && this.readOnly.equals("readonly")) {
			return true;
		}
		return false;
	}

	public void setComponent(HTMLBasicComponent component) {
		this.component = component;
	}

	public void updatePageElement(HTMLBasicComponent c) throws Exception {
		if (this.action != null && this.action.equals("confirm")) {
			this.saveReportforms();
		}
	}

	public int getColumnCount() {
		return 0;
	}

	public String getColumnName(int index) {
		return null;
	}

	public int getRowCount() {
		return this.entities.size();
	}

	public String getType(int col) {
		return null;
	}

	public void setCondition(String condition) {

	}

	/**
	 * 修改单元值
	 */
	public void modifyEntityAttrCellValue(Element td, Document doc, int row,
			int col) {
		SimpleEntity entity = (SimpleEntity) this.entities.get(row);
		String attrName = td.getAttribute("attrname");
		String value = (String) entity.getAttributes().get(attrName);
		if (value == null) {
			value = "　";
		}
		ExtendElement.replaceElementContext(td, value);
	}
}
